package com.cash.channel.svc.logic;

import com.cash.channel.svc.util.ImageUtil;
import com.cash.channel.api.exception.CashChannelException;
import com.cash.common.storage.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@Slf4j
@Component
public class ImageLogic {

    @Resource
    private StorageService storageService;

    public String uploadBase64Image(String base64File) throws CashChannelException {
        try {
            File imageFile = ImageUtil.base64ToImage(base64File);
            String suffix = imageFile.getAbsolutePath().substring(imageFile.getAbsolutePath().lastIndexOf("."));
            String convertFileName = UUID.randomUUID().toString().substring(0, 5) + suffix;
            //上传图片返回图片路径
            FileInputStream inputStream = new FileInputStream(imageFile);
            String fileUrl = storageService.store(inputStream, 0, null, convertFileName);
            // 临时文件删除。
            imageFile.delete();
            log.info("fileUrl:" + fileUrl);
            return fileUrl;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new CashChannelException("生成图片失败");
        }
    }

}
